<script setup>
import { computed, ref } from 'vue';

const props = defineProps({
    // 半屏时的高度（rpx）
    halfHeight: {
        type: Number,
        default: 500
    },
    // 触发全屏的阈值比例（0-1之间）
    threshold: {
        type: Number,
        default: 0.8
    }
})

const startY = ref(0)
const moveY = ref(0)
const isDragging = ref(false)
const isFullScreen = ref(false)

// 计算当前面板位置
const panelStyle = computed(() => {
    const translateY = Math.max(0, moveY.value)
    const scale = translateY > 0 ? 1 - Math.min(translateY / 1000, 0.1) : 1 // 阻尼效果
    return {
        transform: `translateY(${translateY}px) scale(${scale})`,
        transition: isDragging.value ? 'none' : 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
    }
})

// 触摸开始
const touchStart = (e) => {
    startY.value = e.touches[0].clientY
    isDragging.value = true
}

// 触摸移动
const touchMove = (e) => {
    if (!isDragging.value) return

    const currentY = e.touches[0].clientY
    const diff = currentY - startY.value

    // 添加阻尼效果
    if (diff < 0) {
        moveY.value = diff / 2 // 向上拖动时的阻尼
    } else {
        moveY.value = diff
    }
}

// 触摸结束
const touchEnd = () => {
    isDragging.value = false

    // 获取屏幕高度
    const systemInfo = uni.getSystemInfoSync()
    const screenHeight = systemInfo.windowHeight

    // 计算当前拖动的比例
    const movePercent = Math.abs(moveY.value) / screenHeight

    if (moveY.value < 0 && movePercent > props.threshold) {
        // 超过阈值，全屏显示
        moveY.value = 0
        isFullScreen.value = true
    } else {
        // 未超过阈值，显示半屏
        moveY.value = screenHeight - uni.upx2px(props.halfHeight)
        isFullScreen.value = false
    }
}
</script>

<template>
    <view class="drag-panel" :style="panelStyle" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
        <!-- 拖动条 -->
        <view class="drag-bar">
            <view class="drag-bar-inner"></view>
        </view>

        <!-- 内容插槽 -->
        <slot></slot>
    </view>
</template>

<style lang="scss" scoped>
.drag-panel {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
    z-index: 999;

    .drag-bar {
        height: 80rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        &-inner {
            width: 60rpx;
            height: 8rpx;
            background-color: #ddd;
            border-radius: 4rpx;
        }
    }
}
</style>